package com.marvels.financial.loan.service.impl;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.imageio.ImageIO;

import com.dragon.app.ykd.constant.ApplyNode;
import com.dragon.app.ykd.service.AcLoanApplyNodeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fintech.third.service.message.SmsService;
import com.marvels.common.constants.LoanStateConstant;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.dto.SynLoanStatus2ApplyDTO;
import com.marvels.common.dto.pay.MarvelsPayResultDTO;
import com.marvels.common.dto.pay.McfeRepaymentTradeDetails;
import com.marvels.common.enums.PayStatusEnum;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.CommonProperties;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.financial.consum.FinancialConsumerApproveApi;
import com.marvels.financial.consum.FinancialConsumerLoanApplyApi;
import com.marvels.financial.consum.FinancialConsumerSystemApi;
import com.marvels.financial.consum.FinancialConsumerUmApi;
import com.marvels.financial.funds.dao.McfeBhCashAssignApplyDao;
import com.marvels.financial.loan.api.FinancialILoanAfterInfoApi;
import com.marvels.financial.loan.dao.McfeAttachTypeMappingDao;
import com.marvels.financial.loan.dao.McfeCustomerRepaymentPlanDao;
import com.marvels.financial.loan.dao.McfeLendingProcessDao;
import com.marvels.financial.loan.dao.McfeMailSendParamsDao;
import com.marvels.financial.loan.dto.LoanAfterInfoDTO;
import com.marvels.financial.loan.dto.MailInfoDTO;
import com.marvels.financial.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.financial.loan.dto.McfeAttachTypeMapping;
import com.marvels.financial.loan.dto.McfeLendingProcess;
import com.marvels.financial.loan.dto.McfeMailSendParamsDTO;
import com.marvels.financial.loan.dto.McsmSystemParam;
import com.marvels.financial.loan.dto.PaymentResponse;
import com.marvels.financial.loan.service.ILoanApplyMqProduct;
import com.marvels.financial.loan.service.LoanAuditApi;
import com.marvels.financial.loan.service.LoanPaymentApi;
import com.marvels.financial.pay.service.PayService;


@Service
public class LoanPaymentImpl implements LoanPaymentApi {

	@Autowired
	private McfeAttachTypeMappingDao mcfeAttachTypeMappingMapper;

	@Autowired
	private FinancialConsumerLoanApplyApi consumerLoanApplyApi;

	@Autowired
	private McfeBhCashAssignApplyDao assignApplyDao;

	@Autowired
	private ILoanApplyMqProduct iLoanApplyMqProduct;

	@Autowired
	private FinancialConsumerSystemApi consumerSystemApi;

	@Autowired
	private McfeLendingProcessDao mcfeLendingProcessMapper;

	@Autowired
	private LoanAuditApi loanAuditApi;


	@Autowired
	private McfeMailSendParamsDao paramsDao;

	@Autowired
	private FinancialConsumerUmApi consumerUmApi;

	@Autowired
	private McfeCustomerRepaymentPlanDao planDao;

	@Autowired
	private FinancialConsumerApproveApi consumerApproveApi;


	@Autowired
	private FinancialConsumerSystemApi consumSystemApi;

	@Autowired
	private FinancialILoanAfterInfoApi loanAfterInfoApi;

	@Autowired
	private PayService payService;

	@Value("${config.properties.path}")
	private  String configPropertiesPath;

	@Autowired
	private SmsService smsService;
	@Autowired
	private AcLoanApplyNodeService acLoanApplyNodeService;
	/**
	 *
	* @Title: excuteLoanPayment
	* @Description: 放款主逻辑
	* @param loanId
	* @param status
	* @return
	* @author 李瑶
	* @date 2018年10月17日 下午2:57:00
	 */
	@Override
	public PaymentResponse excuteLoanPayment(String loanId,String status) {
		PaymentResponse response = new PaymentResponse();
		McfeLendingProcess mcfeLendingProcess = mcfeLendingProcessMapper.selectByloanIdAndStatus(loanId, status);
		McamLoanApplyInfoDTO mcamLoanApplyInfo = new McamLoanApplyInfoDTO();
		mcamLoanApplyInfo.setLoanId(loanId);
		McamLoanApplyInfoDTO mcamLoanApplyInfoDTO = consumerApproveApi.selectLoanApplyInfo(mcamLoanApplyInfo);
//		boolean headCutApr = adjustSystemParams(String.valueOf(mcfeLendingProcess.getFundSource()),
//				SystemParamsConstant.LOAN_WITHH_FUND);
//		if (headCutApr) {// 需要扣砍头息
//			// 生成咨询费代扣流水 在代付完之后扣
//			LoanAfterInfoDTO loanAfterInfoDTO = new LoanAfterInfoDTO();
//			loanAfterInfoDTO.setLoanId(loanId);
//			loanAfterInfoDTO.setFundName(mcamLoanApplyInfoDTO.getFundName());// 资金源名称
//			loanAfterInfoDTO.setProductName(mcamLoanApplyInfoDTO.getProductName());// 产品小类名称
//			loanAfterInfoDTO.setCustCardNo(mcamLoanApplyInfoDTO.getCustCardNo());// 客户身份证号
//			loanAfterInfoDTO.setCustName(mcamLoanApplyInfoDTO.getCustName());// 客户名称
//			loanAfterInfoDTO.setChannelCode(mcamLoanApplyInfoDTO.getChannel());// 渠道code
//			loanAfterInfoDTO.setChannelName(mcamLoanApplyInfoDTO.getChannelName());// 渠道名称
//			loanAfterInfoDTO.setProductType(mcamLoanApplyInfoDTO.getProductType());// 产品大类code
//			loanAfterInfoDTO.setProductTypeName(mcamLoanApplyInfoDTO.getProductTypeName());// 产品大类名称
//			loanAfterInfoDTO.setMobile(mcamLoanApplyInfoDTO.getMobileNo());// 客户电话
//			loanAfterInfoDTO.setPaymentBankBranch(mcamLoanApplyInfoDTO.getPaymentBankBranch());// 还款账户分行联行号
//			loanAfterInfoDTO.setPaymentBankHead(mcamLoanApplyInfoDTO.getPaymentBankHead());// 还款账户总行联行号
//			loanAfterInfoDTO.setPaymentAcctNo(mcamLoanApplyInfoDTO.getPaymentAcctNo());// 还款账户卡号
//			loanAfterInfoDTO.setPaymentBankName(mcamLoanApplyInfoDTO.getPaymentBankName());// 还款账户开户行名称
//			loanAfterInfoDTO.setPaymentAcctName(mcamLoanApplyInfoDTO.getPaymentAcctName());// 还款账户名称
//			loanAfterInfoDTO.setConsultingFee(mcfeLendingProcess.getConsultingFee());// 咨询费
//			try {
//				loanAfterInfoApi.initLoanWithholding(loanAfterInfoDTO);
//			} catch (MarvelsBusinessException e) {
//				MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + "loanId" + ",咨询费代扣异常:", e);
//			}
//		}
		PaymentResponse result = null;
		try {
			result = paymentLogic(mcfeLendingProcess, mcamLoanApplyInfoDTO);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>>>>loanId" + loanId + ",放款时:", e);
		}
		if (result == null) {
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId + ",代付交易结果返回为空");
			// 未返回结果做交易处理中处理
			response.setCode("1");
			response.setMsg("交易结果返回为空");
			return response;
		}
		MarvelsLogUtil.getInstance()
				.info(">>>>>>>>>>>>>>loanId" + loanId + ",代付交易结果" + JSONObject.toJSONString(result));
		/*String code = result.getCode();
		if ("0".equals(code)) {//放款成功
			loanSuccessDeal(mcfeLendingProcess);
		}*/
		return result;
	}


	/**
	 * 付款处理
	 * @param mcfeLendingProcess
	 * @param headCutApr
	 * @return
	 */
	public PaymentResponse paymentLogic(McfeLendingProcess mcfeLendingProcess,
			McamLoanApplyInfoDTO mcamLoanApplyInfoDTO) {
		PaymentResponse res = new PaymentResponse();
		String loanId = mcfeLendingProcess.getLoanId();
		try {

			Map<String, String> map = new HashMap<String, String>();
			map.put("loanId", mcfeLendingProcess.getLoanId());
			map.put("requestNo", mcfeLendingProcess.getReqNo());
			map.put("idno", mcfeLendingProcess.getCustCardNo());
			map.put("amount", mcfeLendingProcess.getAviAmount().toString());
			map.put("accountName", mcfeLendingProcess.getReceiveAcctName());
			map.put("bankCardNo", mcfeLendingProcess.getReceiveAcctNo());
			map.put("bankCode", mcfeLendingProcess.getReceiveBankCode());
			map.put("bankName", mcfeLendingProcess.getReceiveBankName());
			map.put("mobileNo", mcfeLendingProcess.getCustMobile());
			//商户承担手续费
			map.put("feeType", "SOURCE");
			//调用支付通道放款接口
			String paymentChannel  = ServerProperties.getValue(configPropertiesPath, "common.properties", "daifu_channel");
			MarvelsPayResultDTO marvelsResultDTO = payService.pay(map,paymentChannel);
			String code = marvelsResultDTO.getCode();
			String msg  = marvelsResultDTO.getMessage();
			McfeRepaymentTradeDetails mcamRepaymentTradeDetails = (McfeRepaymentTradeDetails)marvelsResultDTO.getData();
			MarvelsLogUtil.getInstance()
			.info(">>>>>loanId" + loanId + "放款提交的结果为:" + JSONObject.toJSONString(marvelsResultDTO));
			if("0".equals(code)){
				//放款中--请求成功（即请求已成功发送到代发公司，等待返回结果）
				res.setCode("1");
			}else{
				//放款失败
				res.setCode("-1");
				res.setMsg(msg);
			}

			res.setOrderNumber(mcamRepaymentTradeDetails.getPayOrderNumber());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>loanId" + loanId + "代付交易异常:", e);
			res.setCode("-3");
		}
		return res;
	}




	/**
	 * 发送邮件
	 *
	 * @param loanAudit
	 * @param code
	 */
	public void loanEmail(McamLoanApplyInfoDTO dto) {
		try {
			MailInfoDTO mail = new MailInfoDTO();
			List<MailInfoDTO> mailList = new ArrayList<>();
			List<McfeMailSendParamsDTO> email = null;
			String channelTitle = "";
			mail.setFromAddress("marvel_core@creditseconds.com");
			mail.setSubject("客户已放款成功");
			if ("101".equals(dto.getChannel())) {
				List<McfeMailSendParamsDTO> cc1 = paramsDao.selectByTypeId("LOAN_EMAIL_BS");
				StringBuffer bsmails = new StringBuffer();
				int size = cc1.size();
				for (int i = 0; i < size; i++) {
					if (i < size) {
						bsmails.append(cc1.get(i)).append(";");
					} else {
						bsmails.append(cc1.get(i));
					}
				}
				mail.setToEmails(bsmails.toString());
				channelTitle = "保险";
			} else if ("102".equals(dto.getChannel())) {
				List<McfeMailSendParamsDTO> cc1 = paramsDao.selectByTypeId("LOAN_EMAIL_YS");
				StringBuffer ysmails = new StringBuffer();
				int size = cc1.size();
				for (int i = 0; i < size; i++) {
					if (i < size) {
						ysmails.append(cc1.get(i)).append(";");
					} else {
						ysmails.append(cc1.get(i));
					}
				}
				mail.setToEmails(ysmails.toString());
				channelTitle = "银行";
			} else {
				return;
			}
			List<McfeMailSendParamsDTO> cc2 = paramsDao.selectByTypeId("LOAN_EMAIL_CS");
			StringBuffer csmails = new StringBuffer();
			int size = cc2.size();
			for (int i = 0; i < size; i++) {
				if (i < size) {
					csmails.append(cc2.get(i)).append(";");
				} else {
					csmails.append(cc2.get(i));
				}
			}
			mail.setCcAddress(csmails.toString());

			// 查询二级渠道名称及客户经理姓名
			String orgName = "";
			String employeeName = "";
			// Map result =
			// mpLoanAuditMapper.selectOrgName((String)loanAudit.get("sales"));
			// orgName = (String) result.get("orgName");
			// employeeName = (String) result.get("employeeName");
			// if (StringUtils.isEmpty(orgName) ||
			// StringUtils.isEmpty(employeeName) ) {
			// Map map = mpLoanAuditMapper.selectMap(dto.getLoanId());
			// String sales = map.get("sales")+"";
			// if (StringUtils.isNotEmpty(sales)) {
			// Map<String, Object> retMap =
			// cmsEmployeeInfoService.queryUserInfo(Integer.parseInt(sales));
			// if(retMap != null){
			// employeeName = retMap.get("employee_name")+"";
			// orgName = retMap.get("region_name")+"";
			// }
			// }
			// }
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append(
					"<table width=\"80%\" border=\"1\" bordercolor=\"#f0\" style=\"border-collapse:collapse;text-align: center;margin:0px auto;\">");
			stringBuilder.append(
					"<tr><td>产品名称</td><td>渠道类型</td><td>二级渠道名称</td><td>客户经理姓名</td><td>客户姓名</td><td>客户身份证</td><td>贷款金额（核定）</td><td>贷款期限</td></tr>");
			stringBuilder.append("<tr>");
			stringBuilder.append("<td>").append(dto.getProductName()).append("</td>");
			stringBuilder.append("<td>").append(channelTitle).append("</td>");
			stringBuilder.append("<td>").append(orgName).append("</td>");
			stringBuilder.append("<td>").append(employeeName).append("</td>");
			stringBuilder.append("<td>").append(dto.getCustName()).append("</td>");
			String idcard = dto.getCustCardNo();
			if (idcard != null) {
				idcard = idcard.replace(idcard.subSequence(3, 14), "******");
			} else {
				idcard = "";
			}
			stringBuilder.append("<td>").append(idcard).append("</td>");

			Object amount_actObj = dto.getPrincipalAmtAct();
			BigDecimal amount_act = null;
			if (amount_actObj != null) {
				amount_act = new BigDecimal(amount_actObj.toString());
			} else {
				amount_act = new BigDecimal(0);
			}
			stringBuilder.append("<td>").append(amount_act.setScale(2, BigDecimal.ROUND_HALF_UP).toString())
					.append("</td>");

			stringBuilder.append("<td>").append(dto.getApplyTerms()).append("</td>");
			stringBuilder.append("</tr>");
			stringBuilder.append("</table>");
			mail.setContent(stringBuilder.toString());
			mail.setTimingSendTime(new Date());
			mailList.add(mail);
//			consumerExternalApi.insertBatchMailSingle(mailList);
			MarvelsLogUtil.getInstance().info(">>>>邮件已发送, 收件人 : " + mail.getToEmails());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>发送异常信息邮件失败", e);
		}
	}

	/**
	 * 拼装cash参数
	 *
	 * @param mcfeLendingProcess
	 * @param mcamLoanApplyInfoDTO
	 * @return
	 */
	private String assemblingCashData(McfeLendingProcess mcfeLendingProcess,
			McamLoanApplyInfoDTO mcamLoanApplyInfoDTO) {
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("user_id", "");// 用户id
		jsonObj.put("real_name", mcfeLendingProcess.getCustName());// 姓名
		jsonObj.put("bank_name", mcfeLendingProcess.getReceiveBankName());// 银行名称
		jsonObj.put("card_no", mcfeLendingProcess.getReceiveAcctNo());// 银行卡号
		jsonObj.put("money", dealDecimal(mcfeLendingProcess.getPrincipalAmtAct()));// 扣款金额（分）
		jsonObj.put("fee",dealDecimal(mcfeLendingProcess.getConsultingFee()));// 扣款手续费（分）
		jsonObj.put("pay_summary", mcfeLendingProcess.getProductName());// 备注
		jsonObj.put("cellphnone_nbr", mcfeLendingProcess.getCustMobile());// 电话号码
		jsonObj.put("applicant_id_nbr", mcfeLendingProcess.getCustCardNo());// 身份证
		jsonObj.put("avi_amount", mcfeLendingProcess.getAviAmount());// 到手金额
		jsonObj.put("fund_source", mcfeLendingProcess.getFundSource());
		jsonObj.put("channel_choose", "");
		jsonObj.put("req_no", mcfeLendingProcess.getReqNo());
		jsonObj.put("terms", mcfeLendingProcess.getTerms());
		jsonObj.put("toProName", CommonProperties.getToProName());
		jsonObj.put("toCityName", CommonProperties.getToCityName());
		jsonObj.put("toAccDept", CommonProperties.getToAccDept());
		jsonObj.put("rate", mcamLoanApplyInfoDTO.getRate() == null ? 0 : mcamLoanApplyInfoDTO.getRate());
		return jsonObj.toJSONString();
	}

	/**
	 * 判断系统参数
	 *
	 * @param fundCode
	 * @return
	 */
	@Override
	public boolean adjustSystemParams(String fundCode, String paramsValue) {
		McsmSystemParam mcsmSystemParam=new McsmSystemParam();
		mcsmSystemParam.setParamNames(new String[] { paramsValue });
		List<McsmSystemParam> params = consumSystemApi.paramList(mcsmSystemParam);
		if (params != null && params.size() > 0) {
			String paramValue = params.get(0).getParamValue();
			String[] fundCodes = paramValue.split(",");
			for (String fund : fundCodes) {
				if (fundCode.equalsIgnoreCase(fund.trim())) {
					return true;
				}
			}
		}
		return false;
	}

	public void doCompressByte(byte[] dataBt, String name, ZipOutputStream out) throws IOException {
		if (dataBt.length > 0) {
			out.putNextEntry(new ZipEntry(name));
			// 读取文件的内容,打包到zip文件
			out.write(dataBt);
			out.flush();
			out.closeEntry();
		}
	}

	public void doCompressFile(File file, ZipOutputStream out, BufferedOutputStream bos) throws IOException {
		if (file.exists()) {
			byte[] buffer = null;
			String fname = file.getName();
			if (file.getName().endsWith("png")) {
				buffer = png2jpg(file.getPath());
				int pindex = file.getName().lastIndexOf(".");
				pindex = pindex < 0 ? file.getName().length() : pindex;
				fname = file.getName().substring(0, pindex) + ".jpg";
			} else {
				FileInputStream fis =null;
				try {
					fis= new FileInputStream(file);
					buffer = new byte[fis.available()];
					while ((fis.read(buffer)) > 0) {
				    	fis.read(buffer);
				    }
				} catch (Exception e) {
					MarvelsLogUtil.getInstance().error(">>>>>>流转byte异常",e);
				}finally {
					try {
						if(null!=fis){
							fis.close();
						}
					} catch (Exception e2) {
						MarvelsLogUtil.getInstance().error(">>>>>>流转byte异常",e2);
					}
				}

			}
			out.putNextEntry(new ZipEntry(fname));
			// 读取文件的内容,打包到zip文件
			out.write(buffer);
			out.flush();
			out.closeEntry();
		}
	}

	/**
	 * 查询attachTypeMapping
	 *
	 * @param loanId
	 * @param fundSource
	 * @param atmtTypeString
	 * @param productType
	 * @return
	 */
	private Map<String, String> attachTypeMapping(String loanId, Integer fundSource, StringBuilder atmtTypeString,
			String productType) {
		McfeAttachTypeMapping mcfeAttachTypeMapping = new McfeAttachTypeMapping();
		mcfeAttachTypeMapping.setFundCodeId(fundSource);
		mcfeAttachTypeMapping.setProductType(productType);
		mcfeAttachTypeMapping.setCodeType(MarvelsConstant.ATMT_TYPE_PRODUCT);
		List<McfeAttachTypeMapping> mcfeAttachTypes = mcfeAttachTypeMappingMapper
				.selectAttachTypeMapping(mcfeAttachTypeMapping);
		Map<String, String> atmtMap = new HashMap<String, String>();
		if (mcfeAttachTypes != null && mcfeAttachTypes.size() > 0) {
			for (int i = 0; i < mcfeAttachTypes.size(); i++) {
				McfeAttachTypeMapping mcfeAttachType = mcfeAttachTypes.get(i);
				String localAttachCode = mcfeAttachType.getLocalCode();
				String fundAttachCode = mcfeAttachType.getFundParamsCode();
				atmtMap.put(localAttachCode, fundAttachCode);
				if (i >= mcfeAttachTypes.size() - 1) {
					atmtTypeString.append("'").append(localAttachCode).append("'");
				} else {
					atmtTypeString.append("'").append(localAttachCode).append("',");
				}
			}
		}
		if (StringUtils.isEmpty(atmtTypeString.toString())) {
			atmtTypeString.append("'A','D','SEAL_PDF_14','SEAL_PDF_13','SEAL_PDF_12','SEAL_PDF_15','BAODAN'");
		}
		return atmtMap;
	}

	public byte[] png2jpg(String path) {
		BufferedImage bufferedImage = null;
		try {
			// read image file
			bufferedImage = ImageIO.read(new File(path));
			// create a blank, RGB, same width and height, and a white
			// background
			BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),
					BufferedImage.TYPE_INT_RGB);
			// TYPE_INT_RGB:创建一个RBG图像，24位深度，成功将32位图转化成24位
			newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
			// write to jpeg file
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(newBufferedImage, "jpg", baos);
			// System.out.println("Done");
			return baos.toByteArray();
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>图片处理异常:" + e);
			return null;
		} finally {
			if (bufferedImage != null) {
				bufferedImage.flush();
			}
		}
	}

	/**
	 *
	* @Title: loanPaymentQuery
	* @Description: 放款结果查询-->生成还款计划--（支付公司代发）
	* @param loanId
	* @return
	* @throws MarvelsBusinessException
	* @author
	* @date 2018年11月1日 下午2:20:30
	 */
	@Override
	public PaymentResponse loanPaymentQuery(String loanId) throws MarvelsBusinessException{
		McfeLendingProcess mcfeLendingProcess = mcfeLendingProcessMapper.selectByloanIdAndStatus(loanId, "");
		if (mcfeLendingProcess == null) {
			throw new MarvelsBusinessException("放款申请信息不存在");
		}
		PaymentResponse paymentResponse = new PaymentResponse();
		String orignOrderNumber = mcfeLendingProcess.getOrderNumber();

		MarvelsPayResultDTO marvelsResultDTO = null;
		try {
			MarvelsLogUtil.getInstance().info(
					">>>>>>>>>>>loanId" + loanId + "代付申请单号:orderNum:" + orignOrderNumber);
			String paymentChannel  = ServerProperties.getValue(configPropertiesPath, "common.properties", "daifu_channel");
			marvelsResultDTO = payService.queryPayResult(orignOrderNumber, paymentChannel);
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>>loanId" + loanId + "代付结果查询返回参数:"
					+ net.sf.json.JSONObject.fromObject(marvelsResultDTO));
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>loanId" + loanId + "代付结果查询异常:", e);
		}

		// 0成功 -1失败 1交易处理中
		String orderNumber = null;
		String auditStatus = "";
		String auditMsg = "";
		if(marvelsResultDTO == null){
			auditStatus = "F10";
			auditMsg = "处理中";
		}else{
			String code = marvelsResultDTO.getCode();
			McfeRepaymentTradeDetails mcamRepaymentTradeDetails = (McfeRepaymentTradeDetails)marvelsResultDTO.getData();
			orderNumber = mcamRepaymentTradeDetails.getPayOrderNumber();
			if ("0".equals(code)) {
				//接口调用成功
				String result = mcamRepaymentTradeDetails.getResult();
				if("0".equals(result) || StringUtils.equalsIgnoreCase(PayStatusEnum.SUCCESS.toString(), result)){
					//放款成功
					auditStatus = "F2";
					auditMsg = "放款成功";
					//新增 ac_loan_apply_info 	money_hand_out_uid
					try {
						McfeLendingProcess process = new McfeLendingProcess();
						String reloanFlag =  consumerLoanApplyApi.synchroMoneyHandOutTime(loanId);
						process.setReloanFlag(reloanFlag);
						process.setLoanId(loanId);
						mcfeLendingProcessMapper.updateAuditResult(process);
					} catch (Exception e) {
						MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + loanId + "同步到进件表的放款时间失败:", e);
					}

					loanSuccessDeal(mcfeLendingProcess);

					// 流程新流程节点（贷款确认）
					acLoanApplyNodeService.insertSelective(loanId, ApplyNode.LOAN_REPAYMENT);

				}else if("-1".equals(result) || StringUtils.equalsIgnoreCase(PayStatusEnum.FAIL.toString(), result)){
					//银行代发失败
					auditStatus = "F3";
					auditMsg = marvelsResultDTO.getMessage();
				}else{
					//处理中支付 || 公司返回状态异常 || 未知状态
					auditStatus = "F10";
					auditMsg = "处理中";
				}

			} else {// 剩余状态作交易中处理
				auditStatus = "F10";
				auditMsg = "处理中";
			}

		}

		//记录放款日志
		loanAuditApi.auditCommonDeal(loanId, auditStatus, mcfeLendingProcess.getStatus(), "放款查询", null);

		// 持久化审核信息
		McfeLendingProcess process = new McfeLendingProcess();
		process.setLoanId(loanId);
		process.setOrderNumber(orderNumber);
		int index = StringUtils.indexOf(mcfeLendingProcess.getMsg(), "#");
		if(-1 != index) {
			process.setMsg(StringUtils.substring(mcfeLendingProcess.getMsg(), 0, index));
		}
		process.setMsg(mcfeLendingProcess.getMsg() + "#" + auditMsg);
		process.setStatus(auditStatus);
		if("F2".equals(auditStatus)){
			//自动放款成功
			process.setPassTime(new Date());
			//新增 ac_loan_apply_info 	money_hand_out_uid
			try {
				String reloanFlag =  consumerLoanApplyApi.synchroMoneyHandOutTime(loanId);
				process.setReloanFlag(reloanFlag);
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + loanId + "同步到进件表的放款时间失败:", e);
			}
		}
		process.setUpdatedBy("system");
		process.setOriginalStatus(mcfeLendingProcess.getStatus());
		process.setLoanId(loanId);
		process.setIsBusy("0");// 将审核状态改为空闲
		int countInsert = mcfeLendingProcessMapper.updateAuditResult(process);
		if (countInsert < 1) {
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId + ",持久化审核信息失败");
			throw new MarvelsBusinessException("代付结果查询持久化审核信息失败");
		}
		return paymentResponse;
	}


	/**
	 * 部分资金源放款失败修改进件表状态
	 * @param fundSouce
	 * @param loanId
	 */
	public void partFundLendFailDeal(String fundSouce,String loanId){
		McsmSystemParam mcsmSystemParam=new McsmSystemParam();
		mcsmSystemParam.setParamNames(new String[]{MarvelsConstant.LOAN_FAIL_F99_FUND});
		List<McsmSystemParam> list=consumerSystemApi.paramList(mcsmSystemParam);
		if(list!=null && list.size()>0){
			McsmSystemParam param=list.get(0);
			List<String> listString=Arrays.asList(param.getParamValue().split(","));
			if(listString!=null && listString.size()>0){
				for(String fund:listString){
					if(fund.equals(fundSouce)){
						//更新ac_trace状态
						SynLoanStatus2ApplyDTO synLoanStatus2ApplyDTO=new SynLoanStatus2ApplyDTO();
						synLoanStatus2ApplyDTO.setLoanId(loanId);
						synLoanStatus2ApplyDTO.setOriginalState(LoanStateConstant.F03);
						synLoanStatus2ApplyDTO.setStatus(LoanStateConstant.F99);
						try {
							iLoanApplyMqProduct.synLoanStatus2Apply(synLoanStatus2ApplyDTO);
						} catch (MarvelsBusinessException e) {
							MarvelsLogUtil.getInstance().error(">>>>>loanId:"+loanId+"放款失败处理推消息修改状态异常:",e);
						}

					}
				}
			}
		}
	}





	/**
	 * 处理BigDecimal数据
	 * @param decimal
	 * @return
	 */
	private int dealDecimal(BigDecimal decimal) {
		if (decimal == null) {
			return 0;
		} else {
			decimal = decimal.multiply(new BigDecimal("100"));
			return decimal.intValue();
		}
	}

	/**
	 * 放款成功处理
	 */
	@Override
	public void loanSuccessDeal(McfeLendingProcess mcfeLendingProcess) {
		String loanId = mcfeLendingProcess.getLoanId();
		McamLoanApplyInfoDTO mcamLoanApplyInfo = new McamLoanApplyInfoDTO();
		mcamLoanApplyInfo.setLoanId(loanId);
		McamLoanApplyInfoDTO infoDTO = consumerApproveApi.selectLoanApplyInfo(mcamLoanApplyInfo);
		try {
			LoanAfterInfoDTO LoanAfterInfoDTO = new LoanAfterInfoDTO();
			LoanAfterInfoDTO.setLoanId(loanId);
			LoanAfterInfoDTO.setProductCode(infoDTO.getProductCode());
			LoanAfterInfoDTO.setFundSource(infoDTO.getFundCode());
			LoanAfterInfoDTO.setTenor(infoDTO.getApplyTerms());
			LoanAfterInfoDTO.setDate(new Date());
			LoanAfterInfoDTO.setAmount(infoDTO.getPrincipalAmtAct());
			LoanAfterInfoDTO.setFundName(infoDTO.getFundName());// 资金源名称
			LoanAfterInfoDTO.setProductName(infoDTO.getProductName());// 产品小类名称
			LoanAfterInfoDTO.setCustCardNo(infoDTO.getCustCardNo());// 客户身份证号
			LoanAfterInfoDTO.setCustName(infoDTO.getCustName());// 客户名称
			LoanAfterInfoDTO.setChannelCode(infoDTO.getChannel());// 渠道code
			LoanAfterInfoDTO.setChannelName(infoDTO.getChannelName());// 渠道名称
			LoanAfterInfoDTO.setProductType(infoDTO.getProductType());// 产品大类code
			LoanAfterInfoDTO.setProductTypeName(infoDTO.getProductTypeName());// 产品大类名称
			LoanAfterInfoDTO.setMobile(infoDTO.getMobileNo());// 客户电话
			LoanAfterInfoDTO.setPaymentBankBranch(infoDTO.getPaymentBankBranch());// 还款账户分行联行号
			LoanAfterInfoDTO.setPaymentBankHead(infoDTO.getPaymentBankHead());// 还款账户总行联行号
			LoanAfterInfoDTO.setPaymentAcctNo(infoDTO.getPaymentAcctNo());// 还款账户卡号
			LoanAfterInfoDTO.setPaymentBankName(infoDTO.getPaymentBankName());// 还款账户开户行名称
			LoanAfterInfoDTO.setPaymentAcctName(infoDTO.getPaymentAcctName());// 还款账户名称
			LoanAfterInfoDTO.setPatternType(infoDTO.getPatternCode());
			// 生成还款计划 其中就扣了咨询费 修改了进件表的状态
			loanAfterInfoApi.loanApplySuccess(LoanAfterInfoDTO);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + "loanId" + "自动代扣生成还款计划异常:", e);
		}
		// 成功发邮件
		loanEmail(infoDTO);
	}
}
